package com.ljy.jymail.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ljy.common.to.mq.SeckillOrderTo;
import com.ljy.common.utils.R;
import com.ljy.common.vo.MemberRespVo;
import com.ljy.jymail.seckill.feign.CouponFeignService;
import com.ljy.jymail.seckill.feign.ProductFeignService;
import com.ljy.jymail.seckill.interceptor.LoginUserInterceptor;
import com.ljy.jymail.seckill.service.SeckillService;
import com.ljy.jymail.seckill.to.SeckillSkuRedisTo;
import com.ljy.jymail.seckill.vo.SeckillSessionWithSkus;
import com.ljy.jymail.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("SeckillService")
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";//活动场次缓存前缀

    private static final String SKUKILL_CACHE_PREFIX = "seckill:skus";//商品sku缓存前缀

    private static final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//每个商品的秒杀库存商品信号量+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Dats() {
        //扫描最近三天哪些活动需要参与秒杀
        R session = couponFeignService.getLates3Days();

        if (session.getCode() == 0) {
            //上架商品信息
            List<SeckillSessionWithSkus> data = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            //将商品数据缓存到redis中
            //key 商品的开始时间，结束时间
            //缓存活动信息
            saveSessionInfos(data);
            //缓存商品信息
            saveSessionSkuInfos(data);
        }
    }


    public List<SeckillSkuRedisTo> blockHandler(BlockException e){

        log.error("原来的方法被限流了");
        return null;
    }

    /*
     * 获取当前可以参与秒杀的商品信息
     *
     * */
    @SentinelResource(value = "getCurrentSeckillSkus",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        long now = new Date().getTime();

        //定义受保护的资源
        try(Entry entry = SphU.entry("seckillSkus")) {
            //获取秒杀场次需要的所有商品信息
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long startTime = Long.parseLong(s[0]);
                long endTime = Long.parseLong(s[1]);

                if (now >= startTime && now <= endTime) {
                    //获得当前场次的商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    assert range != null;
                    List<String> list = hashOps.multiGet(range);
                    if (list != null || list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redis = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                            //将随机码屏蔽 如果当前秒杀已经开始，就需要随机码
//                        redis.setRandomCode(null);
                            return redis;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        }catch (BlockException e) {
            //只要被限流就抛出该异常
            log.error("资源被限流",e.getMessage());
        }

        return null;
    }


    /*
     * 获取sku商品的预告信息
     * */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品的key信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //正则：数字+_+skuId

                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //如果当前时间在活动时间内，就返回随机码，否则不返回
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    long now = new Date().getTime();
                    if (now >= startTime && now <= endTime) {
                        //在活动时间内，返回随机码
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }


    /*
     * 加入购物车，付款，返回订单号
     * */
    @Override
    public String kill(String killId, String key, Integer num) {
        long start = System.currentTimeMillis();
        MemberRespVo respVo = LoginUserInterceptor.LoginUser.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验数据合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long now = new Date().getTime();
            long ttlTime = endTime - now;//过期时间
            if (now >= startTime && now <= endTime) {
                //2.校验随机码和商品Id是否正确
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3.验证购物的数量是否合理
                    if (num <= redisTo.getSeckillLimit().intValue()) {
                        //4、验证此人是否已经购买过-幂等性处理,只要秒杀成功，就去redis中标识用户信息
                        //userId_sessionId_skuId
                        String redisKey = respVo.getId() + "_" + skuId;
                        Boolean exist = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttlTime, TimeUnit.MILLISECONDS);//如果不存在就返回true，否则返回false
                        if (exist) {
                            //说明没买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //信号量中取出 库存(信号量)

                            //acquire:阻塞的，不适合在秒杀高并发场景下使用
                            //tryAcquire：非阻塞，尝试获取信号量

                            boolean b = semaphore.tryAcquire(num);
                            //秒杀成功
                            //快速下单,发送mq消息 10ms
                            if (b) {
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setMemberId(respVo.getId());
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                seckillOrderTo.setSkuId(redisTo.getSkuId());

                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                long end = System.currentTimeMillis();
                                System.out.println("花费的时间是:"+(end-start));
                                return timeId;
                            }
                            return null;

                        } else {
                            System.out.println("存在");
                            return null;
                        }
                    } else {
                        System.out.println("库存不够" + redisTo.getSeckillLimit().intValue());
                        return null;
                    }

                }
            } else {
                return null;
            }

        }
        return null;
    }

    //保存活动信息
    public void saveSessionInfos(List<SeckillSessionWithSkus> sessions) {
        if (sessions!=null){
            sessions.stream().forEach(session -> {
                //由于需要时间比较，所以转换为Long值最方便
                //使用开始时间和结束时间作为key，商品skuId作为value
                long start = session.getStartTime().getTime();
                long end = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + start + "_" + end;
                //缓存活动信息
                Boolean aBoolean = redisTemplate.hasKey(key);
                //从左加入
                if (!aBoolean) {
                    //格式：场次id_商品id
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }

    }


    //缓存商品信息
    public void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessions) {
        if(sessions!=null){
            sessions.stream().forEach(session -> {
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    String token = UUID.randomUUID().toString().replace("_", "");
                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                        //准备hash操作的结构
                        //缓存商品
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        //sku基本数据
                        R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(info);
                        }

                        //sku秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //设置当前商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        //TODO:sku-为每一个商品设计随机码(接口幂等性)，只有携带随机码的查询库存，才是秒杀服务下的
                        redisTo.setRandomCode(token);

                        String skuJson = JSON.toJSONString(redisTo);
                        ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), skuJson);

                        //如果当前场次的商品的库存信息已经上架，就不需要上架了
                        //商品的库存信息 要从缓存中进行查询更改,减少信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        //使用分布式信号量(限流)作为库存，即作为商品的秒杀件数
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                    }
                });
            });

        }

    }
}
